package com.mobipe.sutto.core;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;

import com.mobipe.sutto.messagehandler.MessageHandler;

/**
 * 
 */

/**
 * @author kohachiro
 *
 */
public class HandlerRunnable implements Runnable {
	ByteBuffer buffer;
	Object channel;
	/**
	 * 
	 */
	public HandlerRunnable(ByteBuffer buffer, Object channel) {
		System.out.println(channel.toString());
		this.buffer = buffer;
		this.channel = channel;
	}

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		char MethodID = buffer.getChar();
		String name = MessageHandler.GetRequestName.findName(MethodID);
		StringBuffer handlerName = new StringBuffer(MessageHandler.class
				.getName().substring(0,
						MessageHandler.class.getName().lastIndexOf(".") + 1))
				.append(name).append("Handler");
		System.out.println(handlerName);
		System.out.println(buffer.toString());
		System.out.println(channel.toString());
		try {
			Class<?> handerClass = Class.forName(handlerName.toString());
			Method handlerMethod = handerClass.getMethod("invoke",
					ByteBuffer.class, Object.class);
			handlerMethod.invoke(handerClass,
					new Object[] { buffer, channel });			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

}
